package workermanager

import (
	"gitee.com/lyuanbo/stock-plus/internal/svc"
	storagememory "gitee.com/lyuanbo/stock-plus/pkg/stock/storage_memory"
)

type Tasker interface {
	Name() string
	Init()
	Start() // 异步
	Run()   // 同步
}

var (
	tasks    []Tasker
	builders []Builder
	// 任务过滤器
	taskFilter = make(map[string]struct{})
)

type Builder func(svcCtx *svc.ServiceContext, cache *storagememory.Cache) Tasker

func Register(builder Builder) {
	builders = append(builders, builder)
}

func Run(svcCtx *svc.ServiceContext, cache *storagememory.Cache) {
	for _, builder := range builders {
		task := builder(svcCtx, cache)
		if _, ok := taskFilter[task.Name()]; ok {
			panic("task already registered: " + task.Name())
		}
		taskFilter[task.Name()] = struct{}{}

		tasks = append(tasks, task)
		task.Init()
		task.Start()
	}
}
